#!/bin/bash

DIR="$(dirname "$0")"
#space=" "
#cmd=""
#bootorder=""
CONFIGFILE=./config/config
OPTION_LINE=5
bootnum=0
ShowBootOrder=0
SetBootOder=0;
BootOrder=""


for param in $*
do
	if [[ $param =~ "--SetOrder=" ]] ;then
		SetBootOder=1
		temp=`echo $param | awk -F '=' '{print $2}'`
		BootOrder=${temp//,/ }
	else
		ShowBootOrder=1
	fi
done

function getbootsum(){
    local sum=0  #局部变量
	while read line1
	do
	  if [[ $line1 =~ "Boot Option #" ]] ;then
		sum=$(($sum+1))
	  fi
	done < $CONFIGFILE
   
    echo $sum
    return $?
}

bootnum=$(getbootsum)
#echo "bootnum = " $bootnum

function get_line() {
	local lines  #局部变量
    lines=`sed -n -e '/Boot Option #/=' $CONFIGFILE`
	echo $lines
	return $?
}
boot_lines=$(get_line)

function get_help() {
	local line=$(($1+1))
	#echo line
	#echo sed -n ""$line""p"" $CONFIGFILE
    help=`sed -n ""$line""p"" $CONFIGFILE`
	echo $help
	return $?
}
boot_help=$(get_help $boot_lines)

function get_tips() {
	local line=$(($1+2))  #局部变量
	#echo line
	
    tips=`sed -n ""$line""p"" $CONFIGFILE  | sed 's/ /,/g' | awk -F '"' '{print $4}'`
	echo $tips
	return $?
}

function get_BootOrder() {
	num=$#
	#echo $num
	#echo $1
	local array
	for ((i=1;i<=$num;i++))
	do
	   	local line=$((${!i}))
		#echo "line= "$line
		
		arraynum=`sed -n ""$line""p"" $CONFIGFILE | awk -F '#' '{print $2}'`
		arraynum=`echo $arraynum | awk -F '"' '{print $1}'`
		
		arraynum=`expr $arraynum - 1`
		#echo $arraynum
		local valueline=`expr $line + 3`
		value=`sed -n ""$valueline""p"" $CONFIGFILE | awk -F ':' '{print $2}'`
		#echo $value
		array[$arraynum]=$value
		#echo ${array[$arraynum]}
	done
	echo ${array[@]}
	return $?
}

function Set_BootOrder() {
	num=$1
	val=`expr $num \* 2 + 1`
	cfgnum=$#
	if [ "$cfgnum" -ne "$val" ]; then
		echo $cfgnum
		return $?
	fi
	for ((i=2;i<=($num + 1);i++))
	do
	   	local line=$((${!i}))
		#echo "line= "$line
		arraynum=`sed -n ""$line""p"" $CONFIGFILE | awk -F '#' '{print $2}'`
		arraynum=`echo $arraynum | awk -F '"' '{print $1}'`
		local line=$((${!i}+3))
		value1=`sed -n ""$line""p"" $CONFIGFILE | awk -F ':' '{print $2}'`
		temp=`expr $num + 1 + $arraynum`
		value2=$((${!temp}))
		#echo $temp
		#echo $value2
		#echo $value1
		sed -i ${line}"s/$value1/$value2/g" $CONFIGFILE
	done

	echo 0
	return $?
}

boot_tips=$(get_tips $boot_lines)

OLD_IFS="$IFS"
#设置分隔符
IFS=";" 
#如下会自动分隔
tips_arr=($boot_tips)
unset tips_arr[0]
#遍历数组

IFS=" " 

if [ "$ShowBootOrder" -ne "0" ] ;then
	BootOrder=$(get_BootOrder $boot_lines)
    echo "BootOrder:" $BootOrder
	for s in ${tips_arr[@]}
	do
		#echo ${s//,/ }
		willprint=`echo ${s//,/ }| awk -F'Value:' '{if (NF == 0) next; print $2":" $1}' | awk '{gsub(/Value/, ""); print}' `
		echo $willprint
	done
	exit 0;
fi

result=$(Set_BootOrder $bootnum $boot_lines $BootOrder)
if [ "$result" -ne "0" ] ;then
	val=`expr $bootnum \* 2 + 1`
	echo "Set BootOrder Fail,Input  BootOrder Number != $bootnum"
	exit 1;
fi


exit 0;
